package com.sfac.javaSpringBoot.modules.account.dao;

import com.sfac.javaSpringBoot.modules.account.entity.User;
import com.sfac.javaSpringBoot.modules.test.entity.Result;
import com.sfac.javaSpringBoot.modules.test.entity.Search;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * DAO是Data Access Object数据访问接口，数据访问，顾名思义是与数据库打交道，夹在业务逻辑与数据库之间
 *
 *@Repository该注解是告诉Spring，让Spring创建一个名字叫“userDao”的UserDaoImpl实例。当Service需要使用Spring创建的名字叫“userDao”
 * 的UserDaoImpl实例时，就可以使用@Resource(name = "userDao")注解告诉Spring，Spring把创建好的userDao注入给Service即可。
 *
 * @Mapper是数据持久层，用于给mapper接口自动根据一个添加@Mapper注解的接口生成一个实现类
 * 如果在接口类上添加了@Mapper，在编译之后会生成相应的接口实现类
 */


@Repository
@Mapper
public interface UserDao {

    @Insert("insert into account_user (user_name, password, email, user_image, create_date)"+
            " values(#{userName}, #{password}, #{email}, #{userImage}, #{createDate})")
    @Options(useGeneratedKeys=true, keyProperty = "id", keyColumn = "id")
    void insertUser(User user);

    @Select("select * from account_user where user_name = #{userName} or email = #{email}")
    List<User> getUsersByUserNameOrEmail(@Param("userName") String userName,@Param("email") String email);

    @Update("update account_user set user_name = #{userName}, email = #{email} where id=#{id}")
    void updateUser(User user);
    //根据id查询对象
    @Select("select * from account_user  where id = #{id}")
    User getUserById(int id);

    @Delete("delete from account_user where id = #{id}")
    void deleteUserById(int id);


    @Select("<script>"
            +"select * from account_user"    //表名
            +"<where>"
            +"<if test='keyword!=\"\" and keyword != null'>"
            +"and(email like '%${keyword}%' or userName like '%${keyword}%')"   //字段匹配email 或者userName
            +"</if>"
            +"</where>"
            +"<choose>"
            +"<when test='orderBy !=\"\" and orderBy != null'>"
            +"order by ${orderBy} ${direction}"
            +"</when>"
            +"<otherwise>"
            +"order by id desc"
            +"</otherwise>"
            +"</choose>"
            +"</script>")
    List<User> getUsersBySearch(Search search);

    @Select("select * from account_user where user_name = #{userName} and password = #{password}")
    User getUserByUserNameAndPassword(
            @Param("userName")String userName,@Param("password")String password);
}
